const query = require('../db/mysql')
const {success,error} =require('../model/model')
const {md5} = require('utility')
const jwt =require('jsonwebtoken')
class ListController {
   register=async(ctx)=>{
    //注册流程
    const {username,password,nickname} = ctx.request.body;
    // 1. 判断账号是否存在
    const isHaveSql = `select * from users where username="${username}"`
    const isHave = await query(isHaveSql)
    if(isHave.length) {
        ctx.body = error('账号已经存在')
        return;
    }
    // 2. 添加数据库
    const sql = `insert into users(username,password,nickname) values("${username}","${md5(String(password))}","${nickname}")`
    const data = await query(sql)
    ctx.body= data;
   }
   login=async(ctx)=>{
    // 登录流程
    const {username,password} = ctx.request.body
    const sql = `select * from users where username="${username}" and password="${md5(String(password))}"`
    const isHave=await query(sql);
    if(isHave.length) {
        ctx.body=success({
            data: isHave[0],
            token: jwt.sign({id:isHave[0].id, username:isHave[0].username}, '1812b')
        },'登陆成功')
    } else {
        ctx.body=error('账号密码有误')
    }
   }
}

module.exports = new ListController()